﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;

namespace HZ.Supervise.Web.Message
{
    public partial class WarningSetupTimeForCompany_SC : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindSort();
                BindList();
            }
            
        }
        /// <summary>
        /// 绑定下拉框
        /// </summary>
        private void BindSort()
        {
            HZ.Supervise.BLL.BLL_Sort bllSort = new HZ.Supervise.BLL.BLL_Sort();
            DataTable dtSort = bllSort.GetSort();
            ddlDrugSort.DataSource = dtSort;
            ddlDrugSort.DataTextField = "SortName";
            ddlDrugSort.DataValueField = "SortID";
            ddlDrugSort.DataBind();
            ddlDrugSort.Items.Insert(0, "---请选择---");
        }
        /// <summary>
        /// 制定消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnConfirmMessage_Click(object sender, EventArgs e)
        {
            
            //将数据存入数据库
            Model.MessageTypeDetail message = new HZ.Supervise.Model.MessageTypeDetail();
            message.AddTime = DateTime.Now;
           
            if (HZ.Fun.CheckString(hdfRecivedCompany.Value.Trim()) != "")
            {
                message.CompanyId = HZ.Fun.CheckString(hdfRecivedCompany.Value.Trim());
                message.CompanyName = HZ.Fun.CheckString(hdfRecivedCompanyName.Value.Trim());
            }
            else
            {
                message.CompanyName = "所有企业";
            }
            if (HZ.Fun.CheckString(ddlDrugSort.SelectedValue) != "---请选择---")
            {
                message.SortId = HZ.Fun.CheckString(ddlDrugSort.SelectedValue.Trim());//药品分类编号
                message.SortName = HZ.Fun.CheckString(ddlDrugSort.SelectedItem.Text.Trim());//分类名称
            }
            else
            {
                message.SortId = "";
                message.SortName = "所有分类";
            }
            if (HZ.Fun.CheckString(hdfRecivedGoods.Value) != "")
            {
                message.ProductName = HZ.Fun.CheckString(hdfRecivedGoodsName.Value.Trim());
                message.GoodsID = HZ.Fun.CheckString(hdfRecivedGoods.Value.Trim());
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "")
            {
                message.ProductName = "所有药物";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "0")
            {
                message.ProductName = "所有基本药物";
            }
            else if (HZ.Fun.CheckString(hdfRecivedGoods.Value) == "" && ddlSortSource.SelectedValue == "1")
            {
                message.ProductName = "所有非基本药物";
            }
            message.TypeId = int.Parse(ddlType.SelectedValue);
            message.TypeKey = "";
            message.TypeName = ddlType.SelectedItem.Text;
            message.UserId = CurrentAccount.UserID;
            message.Level = ddlLevel.SelectedItem.Text;
            message.Is_Work = false;
            message.MessageDetailId = Guid.NewGuid().ToString();
            message.SqlStringWhere = MakeSqlStringWhere(DateTime.Now);
            message.SqlDescription = MakeSqlDescription();
            message.Days = int.Parse(HZ.Fun.CheckString(txtTimeOfRange.Text.Trim()));
            message.DayType = ddlTime.SelectedItem.Text;
            message.Is_Del = false;//未删除
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            if (ibllMessage.IsExistMessageTypeDetail(message))
            {
                HZ.Web.WebUtil.Alert("规则重复");
                return;
            }
            int i = ibllMessage.InsertIntoMessageTypeDetail(message);
            if (i == 0)
            {
                HZ.Web.WebUtil.Alert("添加失败");
            }
            else
            {
                HZ.Web.WebUtil.Alert("添加成功");
                BindList();
                //清空
              
                txtDrug.Text = "";
                txtCompany.Text = "";
                txtTimeOfRange.Text = "";
                hdfRecivedGoods.Value = "";
                hdfRecivedCompany.Value = "";
                hdfRecivedCompanyName.Value = "";             
                ddlDrugSort.SelectedValue = "---请选择---";
                ddlLevel.SelectedValue = "0";
                ddlTime.SelectedValue = "0";
            }
        }

        /// <summary>
        /// 生成Where语句
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        protected string MakeSqlStringWhere(DateTime time)
        {
            StringBuilder sb = new StringBuilder("", 255);
            if (!string.IsNullOrEmpty(txtTimeOfRange.Text.Trim()))
            {
              
                switch (ddlTime.SelectedItem.Text)
                {

                    case "日":
                        string timeday = string.Format("DATEADD({0},{1}, '{2}')", "day", txtTimeOfRange.Text.Trim(), time);
                        sb.AppendFormat(" OrderTimeFrom>'{1}' and OrderTimeFrom<{0}", timeday, time);
                        break;
                    case "周":
                        string timeweek = string.Format("DATEADD({0},{1}, '{2}')", "week", txtTimeOfRange.Text.Trim(), time);
                        sb.AppendFormat(" OrderTimeFrom>'{1}' and OrderTimeFrom<{0}", timeweek, time);
                        break;
                    case "月":
                        string timemonth = string.Format("DATEADD({0},{1}, '{2}')", "month", txtTimeOfRange.Text.Trim(), time);
                        sb.AppendFormat(" OrderTimeFrom>'{1}' and OrderTimeFrom<{0}", timemonth, time);
                        break;
                }
              
               
               
            }
            if (ddlSortSource.SelectedValue != "")
            {
                sb.AppendFormat(" AND SortSource={0} ", ddlSortSource.SelectedValue.ToString());
            } 
            #region 地区医院
            if (hdfRecivedCompany.Value.Trim() != "")
            {
                sb.AppendFormat(" AND CompanyId IN({0}) ", MakeQueryIn(hdfRecivedCompany.Value.Trim().TrimEnd(',')));
            }
           
            #endregion
            #region 药品
            if (hdfRecivedGoods.Value.Trim() != "")
            {
                sb.AppendFormat(" AND GoodsId IN({0}) ", MakeQueryIn(hdfRecivedGoods.Value.Trim().TrimEnd(',')));
            }
            else
            {
                if (ddlDrugSort.SelectedValue.ToString() != "---请选择---")
                {
                    sb.AppendFormat(" AND SortId='{0}' ", ddlDrugSort.SelectedValue.ToString());
                }
               
            }
            #endregion
            return sb.ToString();
        }

        protected string MakeQueryIn(string msg)
        {
            StringBuilder sb = new StringBuilder();
            string[] arr = msg.Trim().Split(',');
            for (int i = 0; i < arr.Length; i++)
            {
                if (i == 0)
                {
                    sb.AppendFormat("'{0}'", arr[i]);
                }
                else
                {
                    sb.AppendFormat(",'{0}'", arr[i]);
                }
            }
            return sb.ToString();
        }
        /// <summary>
        /// 生成Sql描述语句
        /// </summary>
        /// <returns></returns>
        protected string MakeSqlDescription()
        {
            StringBuilder sb = new StringBuilder("", 255);
            if (!string.IsNullOrEmpty(txtTimeOfRange.Text.Trim()))
            {
                sb.AppendFormat("违规时间为<font color='RED'>{0}</font>{1}", int.Parse(HZ.Fun.CheckString(txtTimeOfRange.Text.Trim())), ddlTime.SelectedItem.Text);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 数据绑定
        /// </summary>
        void BindList()
        {
            int t = 0;
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            Model.MessageTypeDetail messageTypeDetail = new HZ.Supervise.Model.MessageTypeDetail();
            messageTypeDetail.UserId = CurrentAccount.UserID;
            messageTypeDetail.Is_Work = false;
            messageTypeDetail.Is_Del = false;
            gvwWarningStart.DataSource = ibllMessage.GetMessageTypeDetailByType(messageTypeDetail, "10,11,12", AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out t);
            this.AspNetPager1.RecordCount = t;
            gvwWarningStart.DataBind();
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindList();
        }

        /// <summary>
        /// 字符串截取
        /// </summary>
        /// <param name="sString"></param>
        /// <param name="nLeng"></param>
        /// <returns></returns>
        string SubStr(string sString, int nLeng)
        {
            if (sString.Length <= nLeng)
            {
                return sString;
            }
            string sNewStr = sString.Substring(0, nLeng);
            sNewStr = sNewStr + "...";
            return sNewStr;
        }
        /// <summary>
        /// 行数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwWarningStart_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            for (int i = 0; i < gvwWarningStart.Rows.Count; i++)
            {
                //string areaName = ((Label)(gvwWarningStart.Rows[i].Cells[2].FindControl("lblAreaName"))).Text.ToString();
                //((Label)(gvwWarningStart.Rows[i].Cells[2].FindControl("lblAreaName"))).Text = SubStr(areaName, 12);

                string CompanyName = ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblCompanyName"))).Text.ToString();
                if (CompanyName != "")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblCompanyName"))).Text = SubStr(CompanyName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[1].FindControl("lblCompanyName"))).Text = "所有生产企业";
                }
                string productName = ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text.ToString();
                if (productName != "")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text = SubStr(productName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[4].FindControl("lblProductName"))).Text = "所有药品";
                } string SortName = ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text.ToString();
                if (SortName != "---请选择---")
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text = SubStr(SortName, 12);
                }
                else
                {
                    ((Label)(gvwWarningStart.Rows[i].Cells[5].FindControl("lblSortName"))).Text = "所有分类";
                }
            }
        }

        /// <summary>
        /// 删除预警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDelte_Click(object sender, EventArgs e)
        {
            string chkedids = Request.Form["chk"];
            int flag = 1;
            if (string.IsNullOrEmpty(chkedids))
            {
                HZ.Web.WebUtil.Alert("请选择一个规则！");
                return;
            }
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            foreach (var item in chkedids.Split(','))
            {
                flag = ibllMessage.DeleteMessageTypeDetail(item);
            }
            if (flag == 1)
            {
                HZ.Web.WebUtil.Alert("删除成功！");
            }
            else
            {
                HZ.Web.WebUtil.Alert("删除失败！");
            }
            BindList();
        }

        /// <summary>
        /// 启动预警
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnStart_Click(object sender, EventArgs e)
        {

            string chkedids = Request.Form["chk"];
            int flag = 1;
            if (string.IsNullOrEmpty(chkedids))
            {
                HZ.Web.WebUtil.Alert("请选择一个规则！");
                return;
            }
            IBLL.IBLL_MessageTypeDetail ibllMessage = new BLL.BLL_MessageTypeDetail();
            foreach (var item in chkedids.Split(','))
            {
                flag = ibllMessage.WarningSwitch(item, "1");
            }
            if (flag == 1)
            {
                HZ.Web.WebUtil.Alert("启用成功！");
            }
            else
            {
                HZ.Web.WebUtil.Alert("启用失败！");
            }
            BindList();
        }


    }
}
